import msvcrt
import time
import docx
from docx import Document
print('*****请注意！test.txt文档末尾不要有多余空白行，否则自动识别行数会报错。使用软件时关闭test.docx和test1.docx。不要修改test.docx和test1.docx和test.txt文件名，填写完成后可以把文件复制到别处再修改文件名。*****\n\n')
xuanze = int(input('请输入数字1或者2来选择操作\n\n1：自动识别文本文档行数\n2：手动输入文本文档行数\n\n输入数字后按回车继续\n'))
if xuanze == 1:
    h=len(open(r"test.txt",'r').readlines())
elif xuanze == 2:
    h=int(input('请输入一个正整数然后按回车继续：\n'))
else:
    print('输入数字有误，程序结束，请重新点开')
f = open('test.txt','r',encoding='utf8')
doc = Document('test.docx')
line = f.readlines()
tables = doc.tables
table = tables[0]
n = 0
q = 0
i = 1
while i > 0:
    while q < 5:
        a = line[n].strip('\n')
        table.cell(i,q+1).text=a
        n = n+1
        q = q+1
        if(n == h):
            break
    i = i+1
    q = 0
    if(n == h):
        break
#下面代码是删除空白行功能
d = i
x = 0
while d > 0:
    row = table.rows[d]
    row._element.getparent().remove(row._element)
    x = x+1
    if(d+x == 31):#如果test.docx表格行数变了就修改这里
        break
t = time.strftime("%Y%m%d-%H%M", time.localtime())
doc.save(t + '.docx')
print('填写完成!!!')
print("\n请按任意键退出本程序")
ord(msvcrt.getch())
